<script setup>
	import {
		ref,
		reactive,
		onBeforeMount,
		watch,
		nextTick
	} from 'vue'

	import {
		ElCard,
		ElTable,
		ElTableColumn,
		ElMessage,
		ElTag,
		ElButton,
		ElInput
	} from 'element-plus'
	import {
		getConsumablesStoreList
	} from "@/api/ConsumablesStore.js"
	import {
		transferList,
		addTransfer,
		getTransferDetail,
		updateMaterialTransferStatus
	} from "@/api/ConsumablesTransfer.js"
	import ConsumableList from '@/components/ConsumableList.vue'
	import {
		Search,
		Plus,
		Refresh,View
	} from "@element-plus/icons-vue";

	/*******************搜索*************************/
	let searchVal = ref("")
	const search = async () => {
		if (searchVal.value) {
			await getMaterialTransferList({
				orderNo: searchVal.value
			});
		}

	}
	watch(searchVal, async (newVal, _) => {
		if (newVal === "" || newVal.length === 0) {
			await getMaterialTransferList(pagination)
		}
	})


	/************获取耗材调拨数据列表**********/
	let statusList = reactive([{
			key: 0,
			status: "0",
			name: "待调拨"
		},
		{
			key: 1,
			status: "1",
			name: "部分调拨"
		},
		{
			key: 2,
			status: "2",
			name: "已完成调拨"
		},
		{
			key: 3,
			status: "3",
			name: "取消调拨"
		},
	])
	const transferDataList = ref([])
	let pagination = reactive({
		page: 1,
		pageSize: 10,
		currentPage: Number(sessionStorage.getItem("transferCurrentPage")) || 1,
		total: 0
	})
	const getMaterialTransferList = async (data) => {
		const result = await transferList(data);
		if (result?.data) {
			transferDataList.value = result.data.mtlist;
			pagination.total = result.data.total;
		} else {
			transferDataList.value = [];
			pagination.total = 0;
		}


	}
	const handleCurrentChange = (cp) => {
		pagination.currentPage = cp;
		sessionStorage.setItem("transferCurrentPage", JSON.stringify(cp));
		getMaterialTransferList({
			page: cp,
			pageSize: pagination.pageSize
		})
	}
	//修改状态
	const handleUpStatus = async ($event, mtId) => {
		console.log($event, mtId)
		if ($event == 3) {
			ElMessageBox.confirm(
					'取消调拨将无法在操作此数据,请慎重操作！',
					'系统提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'danger',
						center: true,
					}
				)
				.then(async () => {
					await updateMaterialTransferStatus(mtId, Number($event));
					await getMaterialTransferList({
						page: pagination.currentPage,
						pageSize: pagination.pageSize
					});
				})
				.catch(() => {})
		} else {
			await updateMaterialTransferStatus(mtId, Number($event));
			await getMaterialTransferList({
				page: pagination.currentPage,
				pageSize: pagination.pageSize
			});
		}

	}
	/**************耗材调拨添加*************/
	let transferVisible = ref(false);
	const formRef = ref();
	let warehouseList = reactive([])
	let consumableList = ref(null);
	let transferFormData = reactive({
		fromWarehouseId: "",
		toWarehouseId: "",
		remark: "",
		materialTransferDetailList: []
	})
	//验证出库入库是否相同
	const detectionWarehouseEqual = () => {
		if (transferFormData.fromWarehouseId === transferFormData.toWarehouseId) {
			formRef.value.validateField("toWarehouseId", (valid) => {
				if (valid) {
					transferFormData.toWarehouseId = ""
					ElMessage.error('出库入库不能相同')
				}
			})
		}
	}

	// 获取子组件选择借用的资产

	const handleAssetSelect = (list) => {
		transferFormData.materialTransferDetailList = [];
		for (let item of list) {
      let newObj = {
        "materialId": 0,
        "materialCode": "",
        "materialName": "",
        "serialUnit": "",
        "materialCategory": "",
        "materialSpecification": "",
        "transferCount": 0,
        "categoryId": 0
      }
			newObj.materialId = item.materialId;
			newObj.materialCode = item.code;
			newObj.materialName = item.name;
			newObj.serialUnit = item.unit;
			newObj.materialCategory = item.categoryName;
			newObj.materialSpecification = item.specification;
			newObj.transferCount = item.materialNum;
			newObj.categoryId = item.categoryId;
			transferFormData.materialTransferDetailList.push(newObj);
		}
	}

  const sendTransferData = () => {
		if (!formRef) return
		formRef.value.validate(async (valid) => {
			if (valid) {
				const result = await addTransfer(transferFormData)
				if (result.code === 200) {
					ElMessage({
						message: "调拨成功",
						type: "success",
						onClose: () => {
							transferVisible.value = false
							getMaterialTransferList(pagination)
						}
					})
				}
			}
		})
	}
	/************** 调拨数据详情 ***********/
	let transferDetailVisible = ref(false);
	const transferDataDetailData = ref([])
	const handleTransferDetailData = async id => {
		transferDetailVisible.value = true
		const result = await getTransferDetail(id)
		if (result.data) {
			transferDataDetailData.value = result.data
		}
	}

	//打开抽屉 重置数据
	const resetTransferFormData = () => {
		formRef.value.resetFields();
	}
	/*********** 页面加载时获取数据 *********/
	onBeforeMount(async () => {
		//获取耗材调拨数据列表
		await getMaterialTransferList({
			page: pagination.currentPage,
			pageSize: pagination.pageSize
		});
		getConsumablesStoreList().then(res => {
			warehouseList = res.data
		})
	})
</script>

<template>

	<div class="materialTransfer">
		<el-space>
			<el-input style="width: 300px" placeholder="请输入关键字" v-model="searchVal" :clearable="true"
				@keydown.enter="search" :prefix-icon="Search">
				<template #append>
					<el-button type="primary" color="#33cbcc" class="searchIcon" :icon="Search"
						@click="search">搜索</el-button>
				</template>
			</el-input>
			<el-button type="primary" class="btn-add" plain :icon="Plus" @click="transferVisible=true">
				调拨
			</el-button>

		</el-space>
		<!-耗材调拨列表->
			<el-table :data="transferDataList" table-layout="auto" height="86%" style="margin:10px 0 0 0;">
        <el-table-column label="调拨单号" prop="orderNo" align="left"/>
        <el-table-column prop="operator" label="经办人" align="center"/>
        <el-table-column prop="status" label="调拨单状态">
          <template #default="scope">
            <el-dropdown @command="handleUpStatus($event,scope.row.id)"
							:disabled="scope.row.lockStatus==1?true:false">
              <el-tag type="danger" v-if="scope.row.status==='0'">待调拨</el-tag>
              <el-tag type="primary" v-if="scope.row.status==='1'">部分调拨</el-tag>
              <el-tag type="success" v-if="scope.row.status==='2'">已完成</el-tag>
              <el-tag type="warning" v-if="scope.row.status==='3'">已取消</el-tag>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="item in statusList" :command="item.status">{{ item.name }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </template>
        </el-table-column>

        <el-table-column prop="fromName" label="调出仓库" align="center"/>
        <el-table-column prop="toName" label="调入仓库" align="center"/>
				<el-table-column prop="createTime" label="创建时间" align="center" />
				<el-table-column label="操作" width="100" align="center">
					<template #default="scope">
            <el-link link type="primary" :icon="View" @click="handleTransferDetailData(scope.row.id)">查看</el-link>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination v-model:current-page="pagination.currentPage" :page-size="pagination.pageSize"
				layout=" slot,prev, pager, next" :total="pagination.total" @current-change="handleCurrentChange">
				<el-text key="1">总条数：{{ pagination.total }}</el-text>
			</el-pagination>


			<!--  添加耗材调拨-->
			<el-drawer v-model="transferVisible" title="添加调拨" size="60%" @closed="resetTransferFormData">
				<el-form :model="transferFormData" ref="formRef" label-width="80px">
					<el-form-item label="出库仓库" prop="fromWarehouseId" :rules="[{required:true,message:'请选择出库仓库'}]">
						<el-select v-model="transferFormData.fromWarehouseId" placeholder="请选择出库仓库"
							style="width: 300px">
							<el-option v-for="fk in warehouseList" :label="fk.name" :value="fk.id" :key="fk.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="入库仓库" prop="toWarehouseId" :rules="[{required:true,message:'请选择入库仓库'}]">
						<el-select v-model="transferFormData.toWarehouseId" placeholder="请选择入库仓库" style="width: 300px"
							@change="detectionWarehouseEqual">
							<el-option v-for="rk in warehouseList" :label="rk.name" :value="rk.id" :key="rk.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="备注" class="full-width">
						<el-input type="textarea" resize="none" :rows="2" v-model="transferFormData.remark"
							placeholder="请填写备注" clearable />
					</el-form-item>
					<ConsumableList ref="consumableList" :wid="transferFormData.fromWarehouseId"
						@consumableSelect="handleAssetSelect" />

					<div class="dialog-footer">
						<el-button type="primary" class="addBtn" @click="sendTransferData">添加</el-button>
					</div>
				</el-form>
			</el-drawer>

			<!--查看调拨详情-->
			<el-drawer v-model="transferDetailVisible" title="调拨详情" size="50%">
        <el-descriptions label-width="80" :column="3" border>
					<el-descriptions-item>
						<template #label>调拨状态</template>
						<el-tag type="danger" v-if="transferDataDetailData.status==='0'">待调拨</el-tag>
						<el-tag type="primary" v-if="transferDataDetailData.status==='1'">部分调拨</el-tag>
						<el-tag type="success" v-if="transferDataDetailData.status==='2'">已完成</el-tag>
						<el-tag type="warning" v-if="transferDataDetailData.status==='3'">已取消</el-tag>
					</el-descriptions-item>
					<el-descriptions-item>
						<template #label>调拨编号</template>
						{{ transferDataDetailData.orderNo }}
					</el-descriptions-item>
					<el-descriptions-item>
						<template #label>调拨人</template>
						{{ transferDataDetailData.operator }}
					</el-descriptions-item>
					<el-descriptions-item>
						<template #label>出仓库</template>
						{{ transferDataDetailData.fromName }}
					</el-descriptions-item>
					<el-descriptions-item>
						<template #label>入仓库</template>
						{{ transferDataDetailData.toName }}
					</el-descriptions-item>
					<el-descriptions-item>
						<template #label>调拨时间</template>
						{{ transferDataDetailData.createTime }}
					</el-descriptions-item>
					<el-descriptions-item>
						<template #label>备注</template>
						{{ transferDataDetailData.remark }}
					</el-descriptions-item>
				</el-descriptions>
        <el-table :data="transferDataDetailData.mtdList" border>
          <el-table-column prop="materialCode" label="耗材编码" width="180" align="center"/>
					<el-table-column prop="materialName" label="名称" align="center" />
					<el-table-column prop="materialSpecification" label="规格型号" align="center" />
					<el-table-column prop="serialUnit" label="单位" align="center" />
					<el-table-column prop="materialCategory" label="耗材类别" align="center" />
					<el-table-column prop="transferCount" label="调拨数量" align="center" />
				</el-table>
			</el-drawer>
	</div>
</template>

<style scoped lang='less'>
	.materialTransfer {
		width: 100%;
		height: 100%;
		padding: 10px;
		box-sizing: border-box;
		background-color: #fff;
		border-radius: 5px;

		.el-tag {
			cursor: pointer;
		}


		.searchIcon,
		.btnGre {
			color: #ffffff;
			background-color: #409eff;
			border-bottom-left-radius: 0;
			border-top-left-radius: 0;
		}

		.searchIcon:hover,
		.btnGre:hover {
			background-color: #409eff;
			color: #ffffff;
		}

		.dialog-footer {
			display: flex;
			justify-content: center;

			.addBtn {
				padding: 20px 0;
				width: 30%;
			}
		}


		.el-pagination {
			display: flex;
			justify-content: flex-end;
			margin-top: 20px;
		}
	}
</style>